package com.boot.security.server.ccccc;

import lombok.RequiredArgsConstructor;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

/**
 * @author LF
 * @date 2020/8/17 - 11:42
 */
@Service
@RequiredArgsConstructor
public class DocServiceImpl implements DocService {

    @Autowired
    private  DocRepository docRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public void save(ESDocument esDocument) {
        ESDocument save = docRepository.save(esDocument);
        System.out.println(save.toString());
    }

    @Override
    public void delete(Integer id) {
        docRepository.deleteById(id);
    }

    @Override
    public void getById(Integer id) {
        docRepository.findById(id).orElse(new ESDocument());
    }

    @Override
    public List<ESDocument> getByName(String name, Integer id) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("name", name)).withQuery(matchQuery("id", id)).build();
        List<ESDocument> esDocuments = elasticsearchTemplate.queryForList(searchQuery, ESDocument.class);
        esDocuments.forEach(e-> System.out.println(e.toString()));
        return esDocuments;
    }

    @Override
    public Iterable<ESDocument> search() {
        // 全文搜索关键字
        /*
        String queryString="张三";
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
        requestLogRepository.search(builder) ;
        */
        /*
         * 多条件查询
         */
        QueryBuilder builder = QueryBuilders.boolQuery()
                // .must(QueryBuilders.matchQuery("userName.keyword", "历张")) 搜索不到
                .must(QueryBuilders.matchQuery("parentIds", "郑州未央区")) // 可以搜索
                .must(QueryBuilders.matchQuery("name", "郑州未央区"));
        return docRepository.search(builder) ;
    }
}
